package cn.com.unionlife.hy.system.service.impl;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.unionlife.hy.core.exception.BusinessException;
import cn.com.unionlife.hy.system.mapper.MenuMapper;
import cn.com.unionlife.hy.system.mapper.UserMapper;
import cn.com.unionlife.hy.system.service.UserTranService;

@Transactional(rollbackFor = Exception.class)
@Service("userTranService")
public class UserTranServiceImpl implements UserTranService {

	@Resource(name = "userMapper")
	private UserMapper userMapper;
	
	@Resource(name = "menuMapper")
	private MenuMapper menuMapper;
	@Override
	public void enableUser(String userId, boolean enabled)
			throws BusinessException {
		if(userMapper.countExtUser(userId)>0){
			userMapper.updateExtUser(userId,enabled);
		}else{
			userMapper.insertExtUser(userId,enabled);
		}
	}
	@Override
	public void authorizeOrg(String userId, String[] orgIds)
			throws BusinessException {
		if(StringUtils.isBlank(userId))
			return;
		//先删除所有分配的组织再重新分配
		userMapper.deleteAllAuthorizedOrg(userId);
		//保证分配的组织部重复
		Set<String> orgIdSet = new HashSet<String>();
		if(ArrayUtils.isNotEmpty(orgIds)){
			for(String s : orgIds){
				if(StringUtils.isNotBlank(s)){
					orgIdSet.add(s);
				}
			}
		}
		if(orgIdSet.size() > 0){
			userMapper.authorizeOrg(userId, orgIdSet.toArray(new String[0]));
		}
	}
	@Override
	public void assignMenu(String userId, Long[] menuIds)
			throws BusinessException {
		if(StringUtils.isBlank(userId))
			return;
		//先删除所有分配的菜单再重新分配
		menuMapper.deleteAllUserMenus(userId);
		//保证分配的菜单不重复
		Set<Long> menuIdSet = new HashSet<Long>();
		if(ArrayUtils.isNotEmpty(menuIds)){
			for(Long l : menuIds){
				if(l != null){
					menuIdSet.add(l);
				}
			}
		}
		if(menuIdSet.size() > 0){
			menuMapper.insertUserMenus(userId, menuIdSet.toArray(new Long[0]));
		}
	}

}
